package com.sinaapp.gavinzhang.webserver;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 一个简单的http服务器
 * Created by gavin on 15-8-13.
 */
public class HttpServer {
    //public static final String WEB_ROOT = System.getProperty("user.dir")+ File.separator+"webroot";
    public static final String WEB_ROOT = "/var/www/html/old";
    private static final String SHUTDOWN = "/shutdown";

    private boolean shutdown = false;

    public static void main(String[] args){
        HttpServer server = new HttpServer();
        server.await();
    }

    public void await()
    {
        ServerSocket serverSocket = null;
        int port = 8082;

        try {
            serverSocket = new ServerSocket(port,10, InetAddress.getByName("127.0.0.1"));
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }

        while (!shutdown){

            try {
                final Socket socket = serverSocket.accept();
                try {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    //socket.setSoTimeout(3000);

                    inputStream = socket.getInputStream();
                    Request request = new Request(inputStream);
                    request.parse();


                    outputStream = socket.getOutputStream();

                    Response response = new Response(outputStream);
                    response.setRequest(request);

                    //check servlet
                    if (request.getUri().startsWith("/servlet/")){
                        ServletProcessor processor = new ServletProcessor();
                        processor.process(request,response);
                    }else {
                        response.sendStaticResource();
                    }


                    //response.test();
                    socket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}
